<template>
	<view>
		<u-navbar :isBack="false" title="购物车" titleColor="#fff" :background="{background: 'var(--mainColor)'}">
			<view class="u-p-r-40" slot="right">
			  <text class="u-font-24 text-white" @click="isDelete = !isDelete">{{isDelete? '取消': '管理'}}</text>
			</view>
		</u-navbar>
		<mescroll-body v-if="userCarts1.length>0" ref="mescrollRef" @init="mescrollInit" @down="downCallback" @up="upCallback">
			<!-- 购物车商品 -->
			<view class="">
				<view class="u-m-30 u-p-20 bg-white rounded-20" v-for="(item,indey) in userCarts1" :key="indey">
					<view class="flex flex-column">
						<!-- 店铺名称 -->
						<u-checkbox v-model="item.supplierChecked" @change="checkboxSupplierChange" :name="item.id" shape="circle"
							activeColor="#FF7405">
							<view class="flex align-center justify-center">
								<text class="mx-1 font">{{item.merch_name}}</text>
							</view>
						</u-checkbox>
						<!-- 该店铺商品 -->
						<dy-supplier-carts-item :goodsList="item" :goodsType="5"></dy-supplier-carts-item>
					</view>
				</view>
			</view>
			<!-- <dy-supplier-carts></dy-supplier-carts> -->
			<!-- 为你推荐 -->
			<!-- <view class="u-p-b-30">
				<u-divider bgColor="transparent" fontSize="30" half-width="200" color="#333" borderColor="#6d6d6d">为你推荐</u-divider>
			</view>
			<view class="flex flex-wrap justify-between u-p-x-30">
				<block v-for="(item,index) in goodsList" :key="index">
					<dy-goods-item :item="item"></dy-goods-item>
				</block>
			</view> -->
		</mescroll-body>
		<dy-no-data v-else title="亲，您的购物车空空如也～" url="/pages/tabbar/supplier/supplier"></dy-no-data>
    <!-- 结算 -->
    <view class="position-fixed left-0 right-0 bg-white box-shadow border-top zIndex-1" style="height: 100px;" :style="{bottom: bottomHeight, 'padding-bottom': `calc(50px  + constant(safe-area-inset-bottom))`,'padding-bottom': `calc(50px  + env(safe-area-inset-bottom))` }">
    	<view class="flex align-center justify-between u-p-l-30 u-p-r-20" style="height: 100%">
    		<u-checkbox v-model="isAllChecked"  shape="circle" @change="allChecked"	activeColor="#FF7405">
    			<view class="flex align-center justify-center">
    				<text class="u-m-x-10 u-font-24">全选</text>
    			</view>
    		</u-checkbox>
    		<view class="flex align-center">
    			<view class="flex" v-if="!isDelete">
    				<text class="u-font-24">合计: </text>
    				<text class="u-font-24" style="color: #FF6600;">￥{{totalPrice}}</text>
    			</view>
    			<text class="submitBtn" v-if="!isDelete" @click="submit(1)">去结算 ({{totalNum}})</text>
    			<text class="submitBtn" v-if="isDelete" @click="submit(2)">删除 ({{deleteNum}})</text>
    		</view>
    	</view>
    </view>
    <u-tabbar v-model="current" :list="list" @change="tabbarChange" active-color="#fe582b" inactive-color="#999999"></u-tabbar>
	</view>
</template>

<script>
	import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
  import { mapState, mapMutations, mapActions } from "vuex";
	import { HomeCenterApi, GoodsCenterApi } from '@/api/serves.js'
	export default {
		mixins: [MescrollMixin], // 使用mixin
		data() {
			return {
				list: [{
					iconPath: "/static/tabbar/supplier.png",
					selectedIconPath: "/static/tabbar/supplier-active.png",
					text: '商圈',
            		pagePath: "/pages/tabbar/supplier/supplier"
				},
				{
					iconPath: "/static/tabbar/cart.png",
					selectedIconPath: "/static/tabbar/cart-active.png",
					text: '购物车',
            		pagePath: "/pages/supplierPage/supplierCart/supplierCart"
				},
				{
					iconPath: "/static/tabbar/mine.png",
					selectedIconPath: "/static/tabbar/mine-active.png",
					text: '我的',
            		pagePath: "/pages/supplierPage/supplierMine/supplierMine"
				},
				{
					iconPath: "/static/supplier/tabbar/shopfh.png",
					selectedIconPath: "/static/supplier/tabbar/shopfh.png",
					text: '返回商城',
            		pagePath: "/pages/tabbar/index/index"
				},
				],
				tabbarCurrent: 1,
				goodsList: [], // 各个店铺的 购物车列表
        title: '管理',
        isAllChecked: false,
        isDelete: false
			};
		},
    computed: {
      ...mapState('user', ['userCarts1']),
			bottomHeight() {
				// #ifdef H5 
				return '50px'
				// #endif
				// #ifdef APP-PLUS || MP-WEIXIN
				return 0
				// #endif
			},
			// 总数量
      totalNum() {
				let num = 0
				for (let item of this.userCarts1) {
					for (let v of item.goods_list) {
					  if(v.goodsChecked) num += v.total_num*1
					}
				}
				return num
			},
      // 总价格
      totalPrice() {
        let price = 0
        for (let item of this.userCarts1) {
        	for (let v of item.goods_list) {
        	  if(v.goodsChecked) {
							let a = this.$calc.Mul(v.goods_price, v.total_num)
							price = this.$calc.Add(price, a) 
						} 
        	}
        }
				console.log(price);
        return price
      },
      // 删除的数量
      deleteNum() {
        let num = 0
        for (let item of this.userCarts1) {
        	for (let v of item.goods_list) {
        	  if(v.goodsChecked) num += 1
        	}
        }
        return num
      },
    },
    watch:{
    	userCarts1: {
    		handler(newName, oldName) {
				console.log(newName);
    			for (let item of newName) {
    				if(!item.supplierChecked) {
							this.isAllChecked = false
							return 
						}
    			}
					this.isAllChecked = true
    		},
    		deep: true
    	}
    },
    onShow() {
    	if(this.isLogin) this.$store.dispatch('user/getUserCartsInfo',{ goods_type: 5})
    },
		methods:{
			tabbarChange(e){
				if(e==this.current) return
				uni.redirectTo({
					url: this.list[e].pagePath
				})
			},
			...mapMutations('user', ['CHECKED_ALL1']),
			// 下拉刷新回掉
			downCallback() {
				this.$store.dispatch('user/getUserCartsInfo',{ goods_type: 5 })
				this.mescroll.resetUpScroll() 
			},
			// 上拉加载
			upCallback(page) {
			  HomeCenterApi.getTjGoods({page: page.num}).then(res => {
			    console.log('获取精选好物--为你推荐', res);
					if(res.code == 1){
						if(page.num == 1) this.goodsList = []; //如果是第一页需手动制空列表
						this.goodsList = this.goodsList.concat(res.data); //追加新数据
						 this.mescroll.endByPage(res.data.length, res.totalpage)
					}else {
						this.$toast(res.msg)
						this.mescroll.endErr()
					}
			  })
			},
      // 勾选店铺
      checkboxSupplierChange(e) {
      	// 1、选中店铺，则 现铺商品全勾选
      	// 2、非选中店铺，则 现铺商品全非勾选
        console.log('勾选店铺', e);
        this.CHECKED_ALL1(e)
      },
			// 全选店铺 结算或者删除
      allChecked(e) {
      	for (let item of this.userCarts1) {
      		item.supplierChecked = e.value
      		for (let v of item.goods_list) {
      			v.goodsChecked = e.value
      		}
      	}
      },
			// 结算 删除
      submit(type){
        if(!this.userCarts1.length) return this.$u.toast('购物车暂无商品', 2000)
        if(type == 1){
          if(!this.totalNum) return this.$Toast('选择结算的商品')
          let list = []
          for (let shopCart of this.userCarts1) {
          	let obj = {merch_id: '', goods_id: '', goods_sku_id: ''}
            let goods_id_list = []
            let goods_sku_id_list = []
            for (let item of shopCart.goods_list) {
              if(item.goodsChecked) {
                if(!obj.merch_id) obj.merch_id = shopCart.id
                goods_id_list.push(item.goods_id)
                goods_sku_id_list.push(item.goods_sku_id)
              }
            }
            obj.goods_id = goods_id_list.join(',')
            obj.goods_sku_id = goods_sku_id_list.join(',')
            if(goods_id_list.length) list.push(obj)
          }
          // console.log(list);
          uni.navigateTo({
          	url:'/pages/supplierPage/supplierGoodsOrderAdd/supplierGoodsOrderAdd?type=cart&orderInfo=' + JSON.stringify(list) + '&goodsType=5'
          })
        }  
        if(type == 2) {
          if(!this.deleteNum) return this.$Toast('选择删除的商品')
          let goods_id_list =  []
          let goods_sku_id_list = []
          for (let shopCart of this.userCarts1) {
            for (let item of shopCart.goods_list) {
              if(item.goodsChecked) {
                goods_id_list.push(item.goods_id)
                goods_sku_id_list.push(item.goods_sku_id)
              }
            }
          }
          let params = {
            goods_id: goods_id_list.join(','),
            goods_sku_id: goods_sku_id_list.join(',')
          }
          this.deleteCart(params)
        }
      },
      // 删除
      deleteCart(params) {
				uni.showLoading()
        GoodsCenterApi.deleteCart({ ...params, goods_type: 5 }).then(res=> {
          uni.hideLoading()
          if(res.code == 1) {
            this.isDelete = false
            this.$store.dispatch('user/getUserCartsInfo',{ goods_type: 5 })
						this.$u.toast('删除成功')
          }else {
						this.$u.toast(res.msg)
					}
        })
      },
    
    }
	}
</script>

<style lang="scss" scoped>
.submitBtn {
	padding: 8rpx 30rpx;
	margin-left: 30rpx;
	color: #FF6600;
	font-size: 26rpx;
	border: 1px solid #FF6600; 
	border-radius: 40rpx;
	box-shadow: 0px 0px 10px 0px rgba(53, 52, 47, 0.14);
}
</style>
